package com.xjt.wx_admin.config;

import com.baomidou.mybatisplus.extension.api.R;
import com.xjt.wx_admin.exception.NotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.List;

/**
 * @author
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandlerResolver {


	//捕获器1
	@ExceptionHandler(value = {MissingServletRequestParameterException.class})
	public R<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException ex) {
		if (log.isErrorEnabled()) {
			log.error(ex.getMessage(), ex);
		}
		return R.failed(String.format("缺少必要参数[%s]", ex.getParameterName()));
	}

	/**
	 * 全局异常.
	 *
	 * @param e the e
	 * @return R
	 */
	@ExceptionHandler({SQLException.class,NullPointerException.class})
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public R handleGlobalException(Exception e) {
		log.error("全局异常信息 ex={}", e.getMessage(), e);
		return R.failed("网络连接中");
	}


	/**
	 * validation Exception
	 *
	 * @param exception
	 * @return R
	 */
	@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R handleBodyValidException(MethodArgumentNotValidException exception) {
		List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
		log.error("参数绑定异常,ex = {}", fieldErrors.get(0).getDefaultMessage());
		return R.failed(fieldErrors.get(0).getDefaultMessage());
	}

	/**
	 * validation Exception
	 *
	 * @param exception
	 * @return R
	 */
	@ExceptionHandler({NotLoginException.class})
	@ResponseStatus(HttpStatus.FORBIDDEN)
	public R handleBodyValidException(NotLoginException exception) {
		log.error("请登陆后访问");
		return R.failed(exception.getMessage());
	}
}
